package com.itheima.stargraph.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.stargraph.dto.request.UserLoginReqDTO;
import com.itheima.stargraph.dto.respone.UserLoginResDTO;
import com.itheima.stargraph.mapper.UserMapper;
import com.itheima.stargraph.pojo.User;
import com.itheima.stargraph.service.UserService;
import com.itheima.stargraph.utils.JWTUtils;
import org.springframework.stereotype.Service;

/**
 * 用户业务层实现类
 *
 * @Author mr.wu
 * @Date 2025-6-9 10:48
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public UserLoginResDTO login(UserLoginReqDTO dto) {
        //1.查询是否存在登录用户 select * from sg_user where mobile=? or username=?
        User user = this.lambdaQuery().eq(User::getUsername, dto.getUsername())
                .or()
                .eq(User::getMobile, dto.getUsername())
                .one();
        if(user==null) {
            throw new RuntimeException("用户名或密码错误");
        }

        //2. 判断密码是否正确
        //比较登录明文密码与表中密文密码是否匹配
        boolean result = BCrypt.checkpw(dto.getPassword(), user.getPassword());
        if(!result) {
            throw new RuntimeException("用户名或密码错误");
        }

        //3. 判断是否正常用户
        if(user.getStatus()!=0) {
            throw new RuntimeException("非法用户");
        }

        //4. 生成登录成功用户的令牌
        String token = JWTUtils.createJWT(user.getId(), user.getUsername());

        //5. 封装响应数据
        UserLoginResDTO resDTO = UserLoginResDTO.builder()
                .id(user.getId())
                .name(user.getUsername())
                .avatar(user.getAvatar())
                .token(token)
                .build();

        return resDTO;
    }
}
